"""
钉钉群里面发送文件
"""

from  conf.readConfig import ReadConfig
import requests
import os


def getAccess_token():
    #获取appkey
    appkey = ReadConfig().get_dingding("appkey")
    appsecret = ReadConfig().get_dingding("appsecret")
    url = "https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s" % (appkey , appsecret)
    headers = {
        "Content-Type" : "application/x-www-form-urlencoded"
    }
    data = {
        "appkey" : appkey,
        "appsecret" : appsecret
    }
    r = requests.get(url=url, data = data , headers = headers)
    access_token = r.json()["access_token"]

    return access_token

def getMedia_id():
    access_token = getAccess_token()
    #获取要发送的文件
    path = os.path.join(os.path.join(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]),"report"),"ceshi.png")

    url = r'https://oapi.dingtalk.com/media/upload?access_token=%s&type=file' %access_token
    files = {"media" : open(path, 'rb')}
    data = {
        "access_token": access_token,
        'type': "file"
    }

    r = requests.post(url = url , files = files, data = data)
    json = r.json()

    return json["media_id"]


def SendFile():
    access_token = getAccess_token()
    media_id = getMedia_id()
    #获取chatid
    chatid = ReadConfig().get_dingding("chatid")
    url = 'https://oapi.dingtalk.com/chat/send?access_token=' + access_token

    headers = {
        "Content-Type": 'application/json'
    }
    data = {
        "access_token" : access_token,
        "chatid": chatid,
        'msg': {
            'msgtype': 'file',
            'file': {
                "media_id": media_id
            }
        }
    }
    r = requests.post(url=url ,json= data, headers = headers)
    assert r.status_code == 200

if __name__ == "__main__":
    SendFile()